Page({
  data: {
    imageList: [],
    uploadDate: new Date().toISOString().split('T')[0],
    endDate: new Date().toISOString().split('T')[0],
    startX: 0,
    startY: 0,
    currentIndex: -1,
    remark: '',
    scrollableHeight: 0,
    searchKeyword: '',
    filteredImageList: [],
    editingIndex: -1,
    tempRemark: '',
    searchTypeList: ['按备注', '按上传时间'],
    searchTypeIndex: 0,
    searchPlaceholder: '搜索图片（按备注）',
    activeTab: 0
  },
  onLoad() {
    this.fetchImageList();
    this.calculateScrollableHeight();
  },
  async fetchImageList() {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'http://127.0.0.1:8888/api/images?wxId=205',
          method: 'GET',
          success: resolve,
          fail: reject
        });
      });
      console.log('图片列表请求响应:', res);
      if (res.statusCode === 200) {
        const images = res.data;
        const imageList = images.map(item => ({
          url: `http://127.0.0.1:8888${item.url}`,
          time: item.time,
          slideDistance: 0,
          remark: item.remark || ''
        }));
        this.setData({
          imageList: imageList,
          filteredImageList: imageList
        });
      } else {
        console.error('获取图片列表失败，状态码:', res.statusCode, '响应数据:', res.data);
      }
    } catch (error) {
      console.error('请求出错:', error);
    }
  },
  async chooseImage() {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: resolve,
          fail: reject
        });
      });
      const tempFilePaths = res.tempFilePaths;
      const time = this.data.uploadDate;
      const remark = this.data.remark;
      const uploadRes = await new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'http://127.0.0.1:8888/api/upload',
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            time: time,
            remark: remark,
            wxId: 888
          },
          success: resolve,
          fail: reject
        });
      });
      if (uploadRes.statusCode === 200) {
        const newImage = {
          url: `http://127.0.0.1:8888${uploadRes.data}`,
          time: time,
          slideDistance: 0,
          remark: remark
        };
        const newImageList = [newImage, ...this.data.imageList];
        this.setData({
          imageList: newImageList,
          filteredImageList: newImageList,
          remark: ''
        });
        wx.showToast({
          title: '图片上传成功',
          icon: 'success'
        });
      } else {
        console.error('图片上传失败，状态码:', uploadRes.statusCode, '响应数据:', uploadRes.data);
        wx.showToast({
          title: '图片上传失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('选择或上传图片失败:', error);
      wx.showToast({
        title: '图片上传失败',
        icon: 'none'
      });
    }
  },
  bindDateChange(e) {
    this.setData({
      uploadDate: e.detail.value
    });
  },
  bindRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    });
  },
  bindSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword
    });
    this.filterImages(keyword);
  },
  bindSearchTypeChange(e) {
    const index = e.detail.value;
    const placeholder = index === 0 ? '备注关键字' : '时间格式：YYYY-MM-DD';
    this.setData({
      searchTypeIndex: index,
      searchPlaceholder: placeholder,
      searchKeyword: ''
    });
    this.filterImages('');
  },
  filterImages(keyword) {
    const {
      searchTypeIndex,
      imageList
    } = this.data;
    if (!keyword) {
      this.setData({
        filteredImageList: imageList
      });
      return;
    }
    if (searchTypeIndex === 0) {
      const filtered = imageList.filter(item => {
        return item.remark.includes(keyword);
      });
      this.setData({
        filteredImageList: filtered
      });
    } else {
      const filtered = imageList.filter(item => {
        return item.time.includes(keyword);
      });
      this.setData({
        filteredImageList: filtered
      });
    }
  },
  previewImage(e) {
    const current = e.currentTarget.dataset.url;
    const urls = this.data.filteredImageList.map(item => item.url);
    wx.previewImage({
      current: current,
      urls: urls
    });
  },
  touchStart(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      startX: e.touches[0].clientX,
      startY: e.touches[0].clientY,
      currentIndex: index
    });
    const imageList = this.data.filteredImageList;
    imageList.forEach((item, i) => {
      if (i !== index) {
        item.slideDistance = 0;
      }
    });
    this.setData({
      filteredImageList: imageList
    });
  },
  touchMove(e) {
    const index = e.currentTarget.dataset.index;
    const currentX = e.touches[0].clientX;
    const currentY = e.touches[0].clientY;
    const diffX = currentX - this.data.startX;
    const diffY = currentY - this.data.startY;
    if (Math.abs(diffX) > Math.abs(diffY)) {
      let slideDistance = diffX;
      if (slideDistance > 0) {
        slideDistance = 0;
      } else if (slideDistance < -160) {
        slideDistance = -160;
      }
      const imageList = this.data.filteredImageList;
      imageList[index].slideDistance = slideDistance;
      this.setData({
        filteredImageList: imageList
      });
    }
  },
  touchEnd(e) {
    const index = e.currentTarget.dataset.index;
    const imageList = this.data.filteredImageList;
    if (imageList[index].slideDistance < -80) {
      imageList[index].slideDistance = -160;
    } else {
      imageList[index].slideDistance = 0;
    }
    this.setData({
      filteredImageList: imageList
    });
  },
  async deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const imageList = this.data.filteredImageList;
    const originalIndex = this.data.imageList.findIndex(item => item.url === imageList[index].url);
    const imageUrl = imageList[index].url;
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'http://127.0.0.1:8888/api/delete',
          method: 'POST',
          data: {
            url: imageUrl
          },
          success: resolve,
          fail: reject
        });
      });
      if (res.statusCode === 200) {
        imageList.splice(index, 1);
        this.data.imageList.splice(originalIndex, 1);
        this.setData({
          imageList: this.data.imageList,
          filteredImageList: imageList
        });
        wx.showToast({
          title: '图片删除成功',
          icon: 'success'
        });
      } else {
        console.error('图片删除失败，状态码:', res.statusCode, '响应数据:', res.data);
        wx.showToast({
          title: '图片删除失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('删除请求出错:', error);
      wx.showToast({
        title: '图片删除失败',
        icon: 'none'
      });
    }
  },
  calculateScrollableHeight() {
    wx.getSystemInfo({
      success: (res) => {
        const windowHeight = res.windowHeight;
        const otherHeight = 200;
        const scrollableHeight = windowHeight - otherHeight;
        this.setData({
          scrollableHeight: scrollableHeight
        });
      }
    });
  },
  startEditRemark(e) {
    const index = e.currentTarget.dataset.index;
    const imageList = this.data.filteredImageList;
    this.setData({
      editingIndex: index,
      tempRemark: imageList[index].remark
    });
    wx.showModal({
      title: '编辑备注',
      content: this.data.tempRemark,
      editable: true,
      placeholderText: '请输入备注',
      success: (res) => {
        if (res.confirm) {
          this.saveRemark({
            currentTarget: {
              dataset: {
                index: index
              }
            },
            detail: {
              value: res.content
            }
          });
        } else if (res.cancel) {
          this.setData({
            editingIndex: -1
          });
        }
      }
    });
  },
  saveRemark(e) {
      const index = e.currentTarget.dataset.index;
      const newRemark = e.detail.value;
      const imageList = this.data.filteredImageList;
      const originalIndex = this.data.imageList.findIndex(item => item.url === imageList[index].url);
      imageList[index].remark = newRemark;
      this.data.imageList[originalIndex].remark = newRemark;
      this.setData({
          imageList: this.data.imageList,
          filteredImageList: imageList,
          editingIndex: -1
      });
      wx.showToast({
          title: '备注保存成功',
          icon: 'success'
      });
  },

  // saveRemark(e) {
  //   const index = e.currentTarget.dataset.index;
  //   const newRemark = e.detail.value;
  //   const imageList = this.data.filteredImageList;
  //   const originalIndex = this.data.imageList.findIndex(item => item.url === imageList[index].url);
  //   const imageUrl = imageList[index].url;
  //   // 调用更新备注的接口
  //   wx.request({
  //     url: 'http://127.0.0.1:8888/api/update',
  //     method: 'POST',
  //     data: {
  //       url: imageUrl,
  //       remark: newRemark
  //     },
  //     success: (res) => {
  //       if (res.statusCode === 200) {
  //         imageList[index].remark = newRemark;
  //         this.data.imageList[originalIndex].remark = newRemark;
  //         this.setData({
  //           imageList: this.data.imageList,
  //           filteredImageList: imageList,
  //           editingIndex: -1
  //         });
  //         wx.showToast({
  //           title: '备注保存成功',
  //           icon: 'success'
  //         });
  //       } else {
  //         console.error('更新备注失败，状态码:', res.statusCode, '响应数据:', res.data);
  //         wx.showToast({
  //           title: '备注保存失败',
  //           icon: 'none'
  //         });
  //       }
  //     },
  //     fail: (error) => {
  //       console.error('更新备注请求出错:', error);
  //       wx.showToast({
  //         title: '备注保存失败',
  //         icon: 'none'
  //       });
  //     }
  //   });
  // },

  saveImageToLocal(e) {
    const imageUrl = e.currentTarget.dataset.url;
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              this.downloadAndSaveImage(imageUrl);
            },
            fail: () => {
              wx.showToast({
                title: '未授予保存到相册权限',
                icon: 'none'
              });
            }
          });
        } else {
          this.downloadAndSaveImage(imageUrl);
        }
      }
    });
  },
  downloadAndSaveImage(imageUrl) {
    wx.downloadFile({
      url: imageUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.showToast({
                title: '图片保存成功',
                icon: 'success'
              });
            },
            fail: () => {
              wx.showToast({
                title: '图片保存失败',
                icon: 'none'
              });
            }
          });
        } else {
          wx.showToast({
            title: '图片下载失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '图片下载失败',
          icon: 'none'
        });
      }
    });
  },
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    console.info("index " + index)
    this.setData({
      activeTab: index
    });
  }
});